//
//  IAALoginVC.m
//  iPadAuditAuthorise
//
//  Created by XiangDongMBP on 16/9/2.
//  Copyright © 2016年 XiangDong. All rights reserved.
//

#import "IAALoginVC.h"
#import "IAATabBarVC.h"
#import "GlobalHeader.h"
#import "IAAUrlProtocolMerge.h"
#import "MD5Algorithm.h"

@interface IAALoginVC ()

@property (weak, nonatomic) IBOutlet UIView *centerBgView;
@property (weak, nonatomic) IBOutlet UITextField *organizeTextField;
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UITextField *pwdTextField;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

@end

@implementation IAALoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //設置子Views
    [self initSubViews];
    // 注册
    if (!IAA_APP_DELEGATE.token.length) {
        [self requestRegister:NO];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)initSubViews {
    self.centerBgView.layer.cornerRadius = 8;
    self.centerBgView.layer.borderWidth = 1;
    self.centerBgView.layer.borderColor = [IAA_COLOR_0x129CFF(1.0) CGColor];
    
    self.organizeTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:IAA_USERDEF_ORGANIZEID];
    self.nameTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:IAA_USERDEF_UNAME];
    [self.organizeTextField addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
    [self.nameTextField addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
    [self.pwdTextField addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
    
    self.loginBtn.layer.cornerRadius = 10;
    [self.loginBtn addTarget:self action:@selector(loginBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    IAA_APP_DELEGATE.organizeId = [[NSUserDefaults standardUserDefaults] objectForKey:IAA_USERDEF_ORGANIZEID];
    IAA_APP_DELEGATE.userNo = [[NSUserDefaults standardUserDefaults] objectForKey:IAA_USERDEF_UNAME];
    
    //测试帐号
//    IAA_APP_DELEGATE.organizeId = @"20041";
//    IAA_APP_DELEGATE.userNo = @"888888";
//    IAA_APP_DELEGATE.token = @"92460a06055b4c819dade8c3c180cd38";
    
//    self.organizeTextField.text = @"00001";
//    self.nameTextField.text = @"888888";
//    self.pwdTextField.text = @"112233";
    
//    self.organizeTextField.text = @"10021";
//    self.nameTextField.text = @"2002";
//    self.pwdTextField.text = @"888888";

    self.organizeTextField.text = @"10022";
    self.nameTextField.text = @"2024";
    self.pwdTextField.text = @"123123";
    
//    self.organizeTextField.text = @"00003";
//    self.nameTextField.text = @"0090";
//    self.pwdTextField.text = @"123123";
    
}

#pragma mark - 按键处理
// 限制输入字符串的长度
- (void)textFieldEditChanged:(UITextField *)field {
    NSInteger maxLen = 0;
    if (field == self.organizeTextField) {
        maxLen = IAA_ORGANIZE_ID_LENGTH;
    } else if (field == self.nameTextField) {
        maxLen = IAA_UNAME_LENGTH;
    } else {
        maxLen = IAA_PASSWORD_LENGTH;
    }
    if (field.markedTextRange == nil &&  field.text.length > maxLen) {
        field.text = [field.text substringToIndex:maxLen];
    }
}

- (void)loginBtnTapped:(UIButton *)btn {
//    // 测试用
//    [self jumpToHomeVC];
//    return;
    
    // 校验输入参数
    if (!self.organizeTextField.text.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入网点号"];
        return;
    }
    if (!self.nameTextField.text.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入柜员号"];
        return;
    }
    if (!self.pwdTextField.text.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入密码"];
        return;
    }
    
    // 未注册成功要再去请求注册
    if (!IAA_APP_DELEGATE.token.length) {
        [self requestRegister:YES];
    } else {
        [self requestLogin];
    }
}

- (void)jumpToHomeVC {
    IAA_APP_DELEGATE.jumpToModifyPwd = [self.pwdTextField.text isEqualToString:@"888888"];
    IAATabBarVC * tabVC = [[IAATabBarVC alloc] init];
    [UIApplication sharedApplication].keyWindow.rootViewController = tabVC;
    //转场动画
    CATransition *anim = [CATransition animation];
    //    anim.type = @"rippleEffect";
    anim.duration = 0.3;
    [[UIApplication sharedApplication].keyWindow.layer addAnimation:anim forKey:nil];
}

#pragma mark - 网络请求
- (void)requestRegister:(BOOL)isLogin {
    // 顯示等待圈圈
    MBProgressHUD * hud;
    if (isLogin) {
        hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    }
    
    NSString *urlStr = [IAAUrlProtocolMerge appRegisterAction];
    NSString *appUUID = [[[UIDevice currentDevice].identifierForVendor UUIDString] xd_md5L16String];
    NSDictionary *pars = @{@"appkey"  : IAA_APP_KEY,
                           @"appUUID" : appUUID,
//                           @"md5" : [self allFilesMd5]
                           @"md5": @"abcdefghijk"
                           };
    [XDAFHttpRequest POST:urlStr parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"注册返回:%@", responseObject);
        if ([responseObject[@"resultCode"] isEqualToString:IAA_RESULT_CODE_SUC]) {
            IAA_APP_DELEGATE.token = responseObject[@"token"];
            if (isLogin) {
                [hud hide:NO];
                [self requestLogin];
            }
        } else {
            if (isLogin) {
                [hud hide:NO];
                [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[@"resultMsg"]];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"注册失败:%@", error);
        if (isLogin) {
            [hud hide:NO];
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
        }
    }];
}

- (NSString *)allFilesMd5 {
    NSFileManager *fm = [NSFileManager defaultManager];
    NSString *path = [NSBundle mainBundle].bundlePath;
    NSDirectoryEnumerator *dirEnum = [fm enumeratorAtPath:path];
    NSString *filePath;
    
    BOOL isDir = YES;
    BOOL isExist = NO;
    NSMutableString *mStr = [NSMutableString string];
    while ((filePath = [dirEnum nextObject]) != nil) {
//        NSLog(@"(%zd)%@", i++, filePath);
        NSString *allFilePath = [path stringByAppendingPathComponent:filePath];
        isExist = [fm fileExistsAtPath:allFilePath isDirectory:&isDir];
        if (isExist && !isDir) {
//            NSLog(@"%@", filePath);
            NSData *data = [NSData dataWithContentsOfFile:allFilePath];
            [mStr appendString:[data xd_md5L32String]];
        }
    }
    NSLog(@"和的md5的md5 = %@", mStr.xd_md5L32String);
    
    return mStr.xd_md5L32String;
}

- (void)requestLogin {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    NSString *urlStr = [IAAUrlProtocolMerge appLoginAction];
    NSDictionary *pars = @{@"organizeId"  : self.organizeTextField.text,
                           @"uname" : self.nameTextField.text,
                           @"upass" : self.pwdTextField.text,
                           @"token": IAA_APP_DELEGATE.token};
    [XDAFHttpRequest POST:urlStr parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"登录成功返回%@", responseObject);
        [hud hide:YES];
        if ([responseObject[@"resultCode"] isEqualToString:IAA_RESULT_CODE_SUC]
            || [responseObject[@"resultCode"] isEqualToString:@"0098"]) {
            [[NSUserDefaults standardUserDefaults] setObject:self.organizeTextField.text forKey:IAA_USERDEF_ORGANIZEID];
            [[NSUserDefaults standardUserDefaults] setObject:self.nameTextField.text forKey:IAA_USERDEF_UNAME];
            IAA_APP_DELEGATE.organizeId = self.organizeTextField.text;
            IAA_APP_DELEGATE.userNo = self.nameTextField.text;
            [self jumpToHomeVC];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[@"resultMsg"]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"登录失败%@", error);
        [hud hide:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

@end
